package com.wlcb.jpower.chat.task.action;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlcb.jpower.chat.entity.customer.TblCustomerMsg;
import com.wlcb.jpower.chat.service.customer.CustomerMsgService;
import com.wlcb.jpower.constant.DBConstant;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: liwenfei
 * @time: 2021/1/11 14:32
 */
@Slf4j
@Component("offTask")
public class OffTask {
    @Resource
    private CustomerMsgService customerMsgService;

    public void off() {
        log.info("处理转离线不回复 time：{}" ,new Date().toLocaleString());
        //处理转离线
        List<TblCustomerMsg> offline = customerMsgService.list(new QueryWrapper<TblCustomerMsg>().lambda()
                .eq(TblCustomerMsg::getStatus, DBConstant.CustomerMsgEnum.OFFLINEACCESSED.getType())
                .eq(TblCustomerMsg::getIsDeleted, 0));
        if (offline.size() > 0) {
            List<TblCustomerMsg> offs = new ArrayList<>();
            for (TblCustomerMsg msg : offline) {
                ImChatRecordCache imChatRecordCache = ImChatRecordCache.getInstance(msg.getOpenid());
                List<DataPacket> records = imChatRecordCache.getRecords();
                if (records != null && records.size() > 0) {
                    DataPacket dataPacket = records.get(records.size() - 1);
                    if (System.currentTimeMillis() - dataPacket.getDate() > 1000 * 1800) {
                        TblCustomerMsg customerMsg = new TblCustomerMsg();
                        customerMsg.setStatus(DBConstant.CustomerMsgEnum.WAIT_ACCESS.getType());
                        customerMsg.setId(msg.getId());
                        customerMsg.setCurrentCid("");
                        offs.add(customerMsg);
                    }
                }
                imChatRecordCache.removeCid();
            }
            if (offs.size() > 0) {
                customerMsgService.updateBatchById(offs);
            }
        }
    }
}
